package com.rbcs.flow.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.rbcs.flow.FlowConstants;
import com.rbcs.flow.model.Flow;
import com.rbcs.flow.model.Node;
import com.rbcs.reimb.model.Reimb;
import com.rbcs.reimb.service.ReimbManager;
import com.systop.core.Constants;
import com.systop.core.dao.support.Page;
import com.systop.core.service.BaseGenericsManager;

/**
 * 流程节点管理Manager
 * 
 * @author ShangHua
 * 
 */
@Service
@SuppressWarnings({ "unchecked", "rawtypes" })
public class NodeManager extends BaseGenericsManager<Node> {
	
	@Autowired
	private ReimbManager reimbManager;

	/**
	 * 根据借款流程表ID得到所有的已审核的流程节点表的集合
	 * 
	 * @return
	 */
	public List<Node> getNodesByFlowId(Integer flowId) {
		String hql = "from Node n where n.flow.id = ? and n.status > ? order by n.orderId asc";
		List nodes = getDao().query(hql, new Object[] { flowId, Constants.NO });
		return nodes;
	}

	/**
	 * 根据流程表ID和部门ID得到流程节点表对应的实体
	 * 
	 * @return
	 */
	public Node getNodeInfo(Integer flowId, Integer deptId) {
		String hql = "from Node n where n.flow.id = ? and n.dept.id = ? ";
		Node node = (Node) getDao().findObject(hql,
				new Object[] { flowId, deptId });
		return node;
	}

	/**
	 * 审核节点流程，是根据上一节点是否已经审核确定当时节点未带审核，如果是第一个默认待审
	 * 
	 * @param node
	 * @return
	 */
	public boolean isPendingNode(Node node) {
		if (node == null || node.getOrderId() == null) {
			return false;
		}
		if (node.getOrderId().intValue() > 1) {
			String hql = "from Node n where n.flow.id = ? and n.orderId = ? and n.status = ?";
			Integer preOrderId = node.getOrderId() - 1;
			// 创建待审状态的节点
			Node preNode = findObject(hql, new Object[] {
					node.getFlow().getId(), preOrderId,
					FlowConstants.AUDIT_PASS });
			return preNode != null;
		} else {
			return true;
		}
	}

	/**
	 * 查询待审节点信息，会判断每个节点的上一个节点是否已经审核
	 * 
	 * @param page
	 * @param hql
	 * @param args
	 * @return
	 */
	public Page queryPaddingNodes(Page page, String hql, Object[] args) {
		page = pageQuery(page, hql.toString(), args);
		List<Node> paddingNodes = new ArrayList<Node>();
		for (Object obj : page.getData()) {
			Node node = (Node) obj;
			if (isPendingNode(node)) {
				paddingNodes.add(node);
			}
		}
		page.setData(paddingNodes);
		return page;
	}

	/**
	 * 保存节点审核信息
	 */
	@Transactional
	public void auditNode(Node node) {
		if (node == null) {
			return;
		}
		save(node);
		Flow flow = node.getFlow();
		if (Constants.NO.equals(node.getIsFinance())) {// 部门节点审核
			if (FlowConstants.AUDIT_PASS.equals(node.getStatus())) {// 审核通过
				int maxOrderId = flow.getNodes().size();
				if (node.getOrderId().intValue() == maxOrderId) {// 如果是部门末端节点,则创建财务审核节点
					createFinanceNode(flow, maxOrderId);
				}
			} else {// 审核未通过
				doEndFlow(flow, node.getStatus());// 根据节点状态终止流程
				updateSourceStatus(flow, node.getStatus());// 更新原始单状态
			}
		} else {// 财务节点审核,更新原始单据状态
			doEndFlow(flow, node.getStatus());// 根据节点状态终止流程
			updateSourceStatus(flow, node.getStatus());// 更新原始单状态
		}
	}

	// 末端部门审核通过后，创建财务审核节点
	private void createFinanceNode(Flow flow, int maxOrderId) {
		Node node = new Node();
		node.setOrderId(maxOrderId + 1);
		node.setStatus(FlowConstants.AUDIT_PENDING);
		node.setIsFinance(Constants.YES);
		node.setFlow(flow);
		save(node);
	}

	// 更新流程状态
	private void doEndFlow(Flow flow, String audStatus) {
		flow.setEndDate(new Date());
		flow.setStatus(FlowConstants.FLOW_END);
		getDao().saveOrUpdate(flow);
	}

	// 更新原始单据状态
	private void updateSourceStatus(Flow flow, String audStatus) {
		if (flow.getBorrow() != null) {// 操作借款
			flow.getBorrow().setAudStatus(audStatus);
			getDao().saveOrUpdate(flow.getBorrow());

		} else if (flow.getReimb() != null) {// 报销操作
			flow.getReimb().setAudStatus(audStatus);
			getDao().saveOrUpdate(flow.getReimb());
			Reimb reimb = flow.getReimb();
			if (reimb.getParentReimb() != null) {
				reimbManager.saveParentReimb(reimb.getParentReimb().getId(), audStatus);
			}
		} else if (flow.getBudget() != null) {// 预算操作
			flow.getBudget().setAudStatus(audStatus);
			getDao().saveOrUpdate(flow.getBudget());
		} else if (flow.getProjectBudget() != null) {// 项目预算操作
			flow.getProjectBudget().setAudStatus(audStatus);
			getDao().saveOrUpdate(flow.getProjectBudget());
		} else {
			// to do nothing.
		}
	}

	/**
	 * 将当前登录的用户名称和负责人用户进行比较，高亮显示。
	 * 
	 * @param userName
	 *            当前登录用户名称
	 * @param auditorNames
	 *            节点表中对应的所有审批人
	 * @return
	 */
	public String auditorNames(String userName, String auditorNames) {
		StringBuffer auditorNameBuf = new StringBuffer();
		String[] auditorNameStr = auditorNames.split(",");
		for (int i = 0; i < auditorNameStr.length; i++) {
			if (userName.equals(auditorNameStr[i])) {
				// auditorNameBuf.append("<font color='blue' style='font-weight: bold;'>");
				auditorNameBuf.append("<font color='blue'>");
				auditorNameBuf.append(auditorNameStr[i]).append("</font>");
			} else {
				auditorNameBuf.append(auditorNameStr[i]);
			}
			auditorNameBuf.append(",");
		}
		String auditorName = StringUtils.EMPTY;
		if (auditorNameBuf.length() > 1) {
			auditorName = auditorNameBuf.toString().substring(0,
					auditorNameBuf.length() - 1);
		}
		return auditorName;

	}
}
